package com.example.myxmpp.fragment;


import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.myxmpp.R;
import com.example.myxmpp.activity.ChatActivity;
import com.example.myxmpp.dbhelper.ContactOpenHelper;
import com.example.myxmpp.dbhelper.SmsOpenHelper;
import com.example.myxmpp.provider.ContactsProvider;
import com.example.myxmpp.provider.SmsProvider;
import com.example.myxmpp.service.IMService;
import com.example.myxmpp.utils.ThreadUtils;

import butterknife.ButterKnife;

/**
 * 会话的Fragment
 * A simple {@link Fragment} subclass.
 */
public class SessionFragment extends Fragment {


    private ListView listView;
    private CursorAdapter adapter;


    public SessionFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_session, container, false);
        initView(rootView);
        return  rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        init();
        initData();
        initListener();
        super.onActivityCreated(savedInstanceState);
    }

    private void init() {
        registerContentObserver();
    }

    private  void initListener(){
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Cursor c = adapter.getCursor();
                c.moveToPosition(position);

                //拿到jid-->发送消息的时候需要
                String account = c.getString(c.getColumnIndex(SmsOpenHelper.SmsTable.SESSION_ACCOUNT));
                //拿到nicName显示效果
                String nickname = getNickNameByAccount(account);

                Intent intent = new Intent(getActivity(), ChatActivity.class);
                intent.putExtra(ChatActivity.CLICKACCOUNT,account);
                intent.putExtra(ChatActivity.CLICKNICKNAME,nickname);
                startActivity(intent);
            }
        });
    }

    private  void initData(){

    setOrNotifyAdapter();
    }

    private void initView(View view){
        listView = view.findViewById(R.id.session_listView);

    }

    /**
     * 设置或者更新adapter
     */
    private void setOrNotifyAdapter() {
        //判断adapter是否存在
        if (adapter != null){
            //刷新adapter就行了
            adapter.getCursor().requery();

            return;
        }
        ThreadUtils.runInUIThread(new Runnable() {
            @Override
            public void run() {
                //对应查询记录
                Cursor c = getActivity().getContentResolver().query(SmsProvider.URI_SESSION,null,null,new String[]{
                        IMService.mCurAccount,IMService.mCurAccount},null);

                //假如没有数据
                if (c.getCount() <= 0){
                    return;
                }

                //设置adapter,然后显示数据
                ThreadUtils.runInUIThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter = new CursorAdapter(getActivity(),c) {
                            @Override
                            public View newView(Context context, Cursor cursor, ViewGroup parent) {
                                //TextView tv = new TextView(context);
                                View view = View.inflate(context,R.layout.item_session,null);

                                return view;
                            }

                            @Override
                            public void bindView(View view, Context context, Cursor cursor) {

                                ImageView ivHead = view.findViewById(R.id.head);
                                TextView tvBody = view.findViewById(R.id.body);
                                TextView tvNickName = view.findViewById(R.id.nickname);

                                String body = c.getString(c.getColumnIndex(SmsOpenHelper.SmsTable.BODY));
                                String account = c.getString(c.getColumnIndex(SmsOpenHelper.SmsTable.SESSION_ACCOUNT));
                                String nickName = getNickNameByAccount(account);

                                tvBody.setText(body);
                                tvNickName.setText(nickName);
                            }
                        };
                        listView.setAdapter(adapter);
                    }
                });
            }
        });


    }

    public String getNickNameByAccount(String account){
        String nickName ="";
        Cursor c = getActivity().getContentResolver().query(ContactsProvider.URI_CONTACT,null,ContactOpenHelper.ContactTable.ACCOUNT+"=?",new String[]{account},null);
        if(c.getCount()>0){
            c.moveToFirst();
            nickName = c.getString(c.getColumnIndex(ContactOpenHelper.ContactTable.NICKNAME));
        }

        return  nickName;
    }

    @Override
    public void onDestroy() {
        unRegisterContentObserver();//反注册
        super.onDestroy();
    }

    //创建监听
    MyContentObserver myContentObserver = new MyContentObserver(new Handler());

    //注册监听
    public void registerContentObserver(){
        getActivity().getContentResolver().registerContentObserver(SmsProvider.URI_SMS,true,myContentObserver);
    }

    //反注册监听
    public void unRegisterContentObserver(){
        getActivity().getContentResolver().unregisterContentObserver(myContentObserver);
    }
    /**
     * 监听数据库改变
     */
    class MyContentObserver extends ContentObserver {

        /**
         * Creates a content observer.
         *
         * @param handler The handler to run {@link #onChange} on, or null if none.
         */
        public MyContentObserver(Handler handler) {
            super(handler);
        }

        /**
         * 如果数据库改变会在这个方法收到通知
         * @param selfChange
         * @param uri
         */
        @Override
        public void onChange(boolean selfChange, Uri uri) {
            super.onChange(selfChange, uri);
            // 设置或者更新adapter
            setOrNotifyAdapter();
        }
    }
}
